<!--
 * @Author: 杨光辉(GerhardYang)
 * @Date: 2021-04-21 13:36:40
 * @LastEditors: 杨光辉(GerhardYang)
 * @LastEditTime: 2021-09-26 02:07:30
 * @Description: file content
 * @Copyright: 超图软件华中平台客户中心 (SuperMap Software Co., Ltd. -Central China Platform)
-->
<template>
  <div id="treeSearchResult">
    <div class="card-isExpend" v-show="isExpendCard" @click="isExpend">
      展开结果面板
    </div>
    <a-card
      class="search-result-card"
      title="搜索结果:"
      size="small"
      v-show="visible"
      :bodyStyle="{ 'min-height': '312px' }"
    >
      <div slot="extra">
        <a-form layout="inline" style="float: left">
          <a-form-item>
            <a-button size="small" @click="isExpend" type="link">
              <a-icon type="down"></a-icon>
            </a-button>
            <a-button size="small" @click="onClose" type="link">
              <a-icon type="close"></a-icon>
            </a-button>
          </a-form-item>
        </a-form>
      </div>
      <a-spin v-show="loading" size="large" tip="数据正在查询中······">
        <div
          class="spin-content"
          style="
            width: 100%;
            min-height: 288px;
            margin-top: 12px;
            border: 1px solid #91d5ff;
            background-color: #e6f7ff;
          "
        ></div>
      </a-spin>
      <div class="container" v-show="!loading">
        <a-table
          :columns="alldata.columns"
          :data-source="alldata.tabledata"
          size="small"
          bordered
          :pagination="{ pageSize: 5 }"
          :row-selection="{ onSelect: onSelect, type: 'radio' }"
        >
          <span slot="action" slot-scope="text, record">
            <a-button @click="showPicture(record)" size="small" type="link"
              >图片详情</a-button
            >
          </span>
        </a-table>
      </div>
    </a-card>
    <OpenImg :image="currentImgObj" ref="OpenImg" />
  </div>
</template>

<script>
import L from "leaflet";
import localStorage from "@/utils/localStorage";
import { hideBottomPanel, showBottomPanel } from "@/utils/divResize";
import {
  smSpatialQuery,
  setQueryPermeterGeometry,
} from "@/utils/http/iserverQuery";
import OpenImg from "./OpenImg.vue";
export default {
  data() {
    return {
      imgVisible: false,
      visible: false,
      loading: true,
      alldata: {},
      isExpendCard: false,
      currentTab: "",
      currentData: "",
      SearchDictionary: JSON.parse(localStorage.get("SearchDictionary")),
      currentImgObj: null,
    };
  },
  components: { OpenImg },
  computed: {
    map() {
      return this.$store.state.map;
    },
    featureLayer() {
      return this.$store.state.treeQueryFeatureGroup;
    },
  },
  methods: {
    isExpend() {
      this.visible = !this.visible;
      this.isExpendCard = !this.isExpendCard;
      this.visible ? showBottomPanel() : hideBottomPanel();
    },
    onClose() {
      this.visible = false;

      this.alldata = {};
      if (this.featureLayer) this.featureLayer.clearLayers();
      hideBottomPanel();
    },
    onSelect(record) {
      this.featureLayer.clearLayers();
      let selectFeature = this.alldata.features.filter(
        (feature) => feature.id == record.key
      );

      L.geoJSON(selectFeature, {
        color: "red",
      })
        .addTo(this.featureLayer)
        .bindPopup(this.buildPopupInfo(record))
        .openPopup();

      this.map.fitBounds(this.featureLayer.getBounds());
    },
    buildPopupInfo(record) {
      let content = `<div class="ant-table ant-table-scroll-position-left ant-table-small" style="max-height: 200px;overflow-y: scroll;  border:none;cursor: pointer;">
      					     <div class="ant-table-content">
      					       <div class="ant-table-body">
      					         <table class="">
      					           <thead class="ant-table-thead">
      					           <tr>
      					             <th  class=""><span class="ant-table-header-column"><div><span class="ant-table-column-title">属性名</span><span class="ant-table-column-sorter"></span></div></span></th>
      					             <th  class=""><span class="ant-table-header-column"><div><span class="ant-table-column-title">属性值</span><span class="ant-table-column-sorter"></span></div></span></th>
      					           </tr>
      					           </thead>
      					           <tbody class="ant-table-tbody">`;
      for (let key in record) {
        if (!key.startsWith("Sm") && !key.startsWith("SM")) {
          // 匹配字典表
          let cname = key;
          for (let dict of this.SearchDictionary) {
            if (dict.ename.toUpperCase() == key.toUpperCase()) {
              cname = dict.cname;
              if (record[key] && record[key] != "") {
                // console.log(event.layer.properties.attributes[item]);
                content += `            <tr class="ant-table-row ant-table-row-level-0">
      					                 <td class="" style="border:none">${cname}</td>
      					                 <td class="" style="border:none">${record[key]}</td>
      					               </tr>`;
              }
            }
          }
        }
      }
      content += `
      					           </tbody>
      					         </table>
      					       </div>
      					     </div>
      					   </div>`;
      return content;
    },
    buildResultData(quretResultRecordset) {
      let self = this;
      this.alldata = {};
      //调整样式
      let columns = this.buildColumns(quretResultRecordset);
      let tabledata = this.buildData(quretResultRecordset);

      this.alldata = {
        key: quretResultRecordset.key,
        columns: columns,
        tabledata: tabledata,
        features: quretResultRecordset.result.features.features,
        queryableLayers: quretResultRecordset.queryableLayers,
        mapUrl: quretResultRecordset.mapUrl,
      };

      this.loading = false;

      L.geoJSON(this.currentData.features, {
        color: "red",
      })
        .addTo(this.featureLayer)
        .bindPopup(function (layer) {
          return self.buildPopupInfo(layer.feature.properties);
        });
    },
    buildColumns(quretResultRecordset) {
      let columns = [];
      //TODO 针对地铁站数据添加图标按钮，用于展示地铁站图片数据
      if (quretResultRecordset.key == "地铁站") {
        columns.push({
          title: "图片",
          key: "action",
          scopedSlots: { customRender: "action" },
          width: 140,
          ellipsis: true,
        });
      }
      let feature = quretResultRecordset.result.features.features[0];
      for (let field in feature.properties) {
        const dataIndex = field;
        // 排除系统字段
        if (
          !field.startsWith("Sm") &&
          !field.startsWith("SM") &&
          field != "CROWID"
        ) {
          // 匹配字典表
          for (let dict of this.SearchDictionary) {
            if (dict.ename.toUpperCase() == field.toUpperCase()) {
              field = dict.cname;
            }
          }
          columns.push({
            title: field,
            dataIndex: dataIndex,
            width: 140,
            ellipsis: true,
            defaultSortOrder: "descend",
            sorter: (a, b) => a[dataIndex] - b[dataIndex],
          });
        }
      }
      // console.log(quretResultRecordset.key + "表格表头", columns);
      return columns;
    },
    buildData(quretResultRecordset) {
      let data = [];
      let features = quretResultRecordset.result.features.features;
      for (let feature of features) {
        feature.properties.key = feature.id;
        //data.push(`<a-button type="primary">Primary</a-button>`);
        let properties = feature.properties;
        //TODO 处理数据字典
        for (let element in properties) {
          let value = properties[element];
          properties[element] = this.getDicValue(value, element);
        }
        data.push(properties);
      }
      // console.log(quretResultRecordset.key + "表格数据", data);
      return data;
    },
    getDicValue(value, element) {
      let dicFields = [
        "SFWQ",
        "SFJD",
        "SFJY",
        "SFWX",
        "SFCY",
        "SFZS",
        "SFXSJ",
        "SFGW",
        "SFJJ",
        "SFCLJS",
        "SFYJQSS",
        "SFYCLCDSS",
      ];
      if (dicFields.indexOf(element) >= 0) {
        if (value == 1) {
          return "是";
        } else {
          return "否";
        }
      } else if (element == "LDLMLX") {
        if (value == 11) {
          return "沥青混凝土";
        } else if (value == 12) {
          return "水泥混凝土";
        } else if (value == 21) {
          return "沥青贯入式";
        } else if (value == 22) {
          return "沥青碎石";
        } else if (value == 23) {
          return "沥青表面处治";
        } else if (value == 31) {
          return "砂石路面";
        } else if (value == 32) {
          return "石质路面";
        } else if (value == 33) {
          return "渣石路面";
        } else if (value == 34) {
          return "砖铺路面";
        } else if (value == 35) {
          return "砼预制块";
        } else if (value == 36) {
          return "无路面";
        } else {
          return "";
        }
      } else if (element == "LDJSDJ") {
        if (value == 1) {
          return "高速公路";
        } else if (value == 2) {
          return "一级公路";
        } else if (value == 3) {
          return "二级公路";
        } else if (value == 4) {
          return "三级公路";
        } else if (value == 5) {
          return "四级公路";
        } else if (value == 6) {
          return "等外公路";
        } else {
          return "";
        }
      }
      return value;
    },
    async sqlQuery(sql) {
      let self = this;
      this.loading = true;
      let param = setQueryPermeterGeometry(
        this.currentData.queryableLayers,
        this.$parent.event,
        sql
      );
      let recordsets = await smSpatialQuery(
        param,
        this.$parent.event.layerType,
        this.currentData.mapUrl
      );
      console.log("sqlQuery", recordsets);

      let features = L.Util.transform(
        recordsets[0].features,
        L.CRS.EPSG3857,
        L.CRS.EPSG4326
      );
      this.currentData.features = features.features;
      if (this.currentData.features.length < 1) {
        this.loading = false;
        this.$message.warning("没有查询到数据，请检查查询参数！");
        return false;
      }

      let data = [];
      for (let feature of this.currentData.features) {
        feature.properties.key = feature.id;
        data.push(feature.properties);
      }
      this.currentData.tabledata = data;
      this.alldata = this.alldata.map((item) => {
        if (item.key == this.currentData.key) {
          item = this.currentData;
        }
        return item;
      });

      this.loading = false;
      this.featureLayer.clearLayers();
      L.geoJSON(this.currentData.features, {
        color: "red",
      })
        .addTo(this.featureLayer)
        .bindPopup(function (layer) {
          return self.buildPopupInfo(layer.feature.properties);
        });
    },
    showPicture(record) {
      console.log(record);

      this.currentImgObj = {
        title: `${record.NAME}`,
        imgUrl: "images/地铁站/" + record.NAME + ".png",
      };
      this.$refs.OpenImg.buildData(this.currentImgObj);
    },
  },
};
</script>

<style lang="less" scoped>
.card-isExpend {
  position: fixed;
  z-index: 999;
  left: 40%;
  bottom: 10px;
  width: 200px;
  height: 30px;
  text-align: center;
  line-height: 30px;
  user-select: none;
  cursor: pointer;
  background-color: #fff;
  border-radius: 15px 15px 0 0;
  color: rgba(0, 0, 0, 0.85);
  border: 1px solid #d9d9d9;
}
.search-result-card {
  position: fixed;
  z-index: 99;
  right: 350px;
  left: 0;
  z-index: 999999;
  bottom: 0;
  .container {
    padding-top: 16px;
    height: 312px;
    overflow: scroll;
  }
}
/deep/.ant-card-extra {
  padding: 0 !important;
}
/deep/.ant-card-body {
  padding-top: 0 !important;
  padding-bottom: 0 !important;
}
/deep/.ant-tabs-bar {
  margin: 0 !important;
}
/deep/.ant-table-pagination.ant-pagination {
  margin: 5px 0 !important;
  float: right;
}
/deep/.ant-table-body {
  overflow-x: scroll;
}
/deep/.ant-card-small
  > .ant-card-head
  > .ant-card-head-wrapper
  > .ant-card-extra {
  padding: 0;
}
</style>
